package com.sjz.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


/**
 * 得到安卓端传过来的数据  get和post  文件上传的方式
 */
public class ManageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String title = request.getParameter("title");		
		String timelength = request.getParameter("timelength");
		System.out.println("视频名称："+ title);
		System.out.println("时长："+ timelength);
	}

	 
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if(isMultipart){  //得到请求类型  如果是文件上传  
			try{
				FileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory); //基于磁盘保存
				upload.setHeaderEncoding("UTF-8");
				List<FileItem> items = upload.parseRequest(request);
				//把上传的内容转换成FileItem  既有文本又有文件
				//得到文件上传路径  
				String dir = request.getSession().getServletContext().getRealPath("/files");
				File dirFile = new File(dir);
				if(!dirFile.exists()) dirFile.mkdirs();
				for(FileItem item : items){  //遍历所有的请求参数 
					if(item.isFormField()) {//如果文本类型参数
						String name = item.getFieldName();
						String value = item.getString("UTF-8");
						System.out.println(name+ "="+ value);
					}else{//如果文件类型参数
						System.out.println(dir);
						File saveFile = new File(dirFile, item.getName());
						item.write(saveFile);
					}
				}
			}catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			//如果不是文件上传
			doGet(request, response);
		}
	}

}
